<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('成绩录入')"/>
    <th:block th:include="include :: select2-css"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: summernote-css" />
    <style>
        .form-control {
            width: 118px;
            margin-bottom: 4px;
        }

        .train-account {
            display: none;
        }

        .item {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            border-bottom: 1px solid #ddd;
            border-right: 1px solid #ddd;
            background: #f8f8f8;
            border: solid 1px #58a1bb;
        }

        .sub-item {
            width: 160px;
            flex-shrink: 1;
            border-left: 1px solid #ddd;

        }

        .title {
            width: 100%;
            height: 50px;
            border-top: 1px solid #ddd;
            border-bottom: 1px solid #ddd;
            padding: 15px;
            font-weight: bold;
            text-align: center;
            background: #dee1e1;
        }
        .title-red {
            background: rgba(255, 5, 23, 0.25);
        }

        .content {
            min-height: 100px;
            padding: 10px;
            cursor: pointer;
        }

        .content p {
            line-height: 100px;
            text-align: center;
        }
        .save-score-btn{
            display: none;
        }
        .note-editor .panel-heading {
            padding: 0px 5px;
        }
        .note-editor .btn-sm, .note-editor .btn-xs {
            padding: 1px 5px;
            font-size: 12px;
            line-height: 1.5;
            border-radius: 3px;
        }
        .content p {
             line-height: 17px;
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="col-sm-12 search-collapse">
        <form id="data-form" >
            <input id="childCourseId" name="childCourseId" th:value="*{childCourseId}" hidden="true">
            <div class="row">
                <div class="col-xs-12">
                    <div class="text-right">
                        <div id="saveScoreBth" style="display: inline">
                            <button th:if="${scoreFlag==0}" style="width: 100px;margin-top: 10px" type="button" onclick="submitScore()"
                                    class="btn btn-primary">提交成绩
                            </button>
                            <button th:if="${scoreFlag==0}" style="width: 100px;margin-top: 10px" type="button" onclick="saveScore()"
                                    class="btn btn-primary">保存记录
                            </button>
                        </div>
                        <button style="width: 100px;margin-top: 10px" type="button" onclick="closeItem()"
                                class="btn btn-danger">关闭
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: select2-js"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:include="include :: summernote-js" />
<script th:inline="javascript">
    // 权限
    // 字典
    var prefix = ctx + "business/courseChildScore";
    var childIds = [];
    var bzName=[];
    $(function () {
        //获取数据
        $.ajax({
            url: prefix + "/list?childCourseId=" + $("#childCourseId").val(),
            type: 'GET',
            error: function (request) {
                $.modal.alertError("系统错误");
            },
            success: function (data) {
                if (data.data.length > 0) {
                    var html = "";
                    for (var i in data.data) {
                        var obj = data.data[i];
                        childIds.push(obj.childId);
                        html += "<div id='" + obj.childId + "' style=\"width: 100%;margin-top: 10px;\">\n" +
                            "                <div class=\"item\">\n" +
                            "                    <div class=\"sub-item\" style='width: 80px'>\n" +
                            "                        <div class=\"title\">学员</div>\n" +
                            "                        <div class=\"content\">\n" +
                            "                            <p>" + obj.childName + "</p>\n" +
                            "                        </div>\n" +
                            "                    </div>";
                        var questionOne = JSON.parse(obj.linkOneQuestion);
                        html += initQuestion(obj.childId, "link1", obj.linkOne, questionOne,obj.linkOneScore);

                        var questionTwo = JSON.parse(obj.linkTwoQuestion);
                        html += initQuestion(obj.childId, "link2", obj.linkTwo, questionTwo,obj.linkTwoScore);

                        var questionThree = JSON.parse(obj.linkThreeQuestion);
                        html += initQuestion(obj.childId, "link3", obj.linkThree, questionThree, obj.linkThreeScore);

                        var questionFour = JSON.parse(obj.linkFourQuestion);
                        html += initQuestion(obj.childId, "link4", obj.linkFour, questionFour, obj.linkFourScore);

                        var questionFive = JSON.parse(obj.linkFiveQuestion);
                        html += initQuestion(obj.childId, "link5", obj.linkFive, questionFive, obj.linkFiveScore);

                        var questionSix = JSON.parse(obj.linkSixQuestion);
                        html += initQuestion(obj.childId, "link6", obj.linkSix, questionSix, obj.linkSixScore);

                        var questionSeven = JSON.parse(obj.linkSevenQuestion);
                        html += initQuestion(obj.childId, "link7", obj.linkSeven, questionSeven, obj.linkSevenScore);

                        var questionEight = JSON.parse(obj.linkEightQuestion);
                        html += initQuestion(obj.childId, "link8", obj.linkEight, questionEight, obj.linkEightScore);

                        var questionNine = JSON.parse(obj.linkNineQuestion);
                        html += initQuestion(obj.childId, "link9", obj.linkNine, questionNine, obj.linkNineScore);

                        // if(obj.childId !=null && obj.childId!=0){
                        //     html += "<div id='basic_" + obj.childId + "' class=\"sub-item\" style='width: 75px'>\n" +
                        //         "                        <div class=\"title\">操作</div>\n" +
                        //         "                        <div class=\"content\">\n" +
                        //         "                            <a style='text-decoration: underline;' onclick='editBasicExpression("+obj.childCourseId+","+obj.childId+")'>基础表现</a>\n" +
                        //         "\n" +
                        //         "                        </div>\n" +
                        //         "                    </div>";
                        // }else {
                        //     html += "<div id='basic_" + obj.childId + "' class=\"sub-item\" style='width: 75px'>\n" +
                        //         "                        <div class=\"title\">操作</div>\n" +
                        //         "                        <div class=\"content\">\n" +
                        //         "\n" +
                        //         "                        </div>\n" +
                        //         "                    </div>";
                        // }

                        html += " </div></div>";


                    }
                    $("#data-form").prepend(html);
                }

                $('.summernote').summernote({
                    lang: 'zh-CN',
                    width:150,
                    minHeight:90,
                    toolbar:[
                        ['font',['strikethrough']],
                    ],
                    lineHeight:20
                });
            }
        })


    });

    function initQuestion(childId, linkName, projectName, questionObj,oldScore) {
        if(questionObj ==null){
            projectName="",childId="";
        }

        if(projectName =="null"){
            projectName= "";
        }
        var html = "";
        oldScore = JSON.parse(oldScore);
        html += "<div  class=\"sub-item\">\n" +
            "     <div id='title_" + childId + '_' + linkName + "' class=\"title\">" + projectName + "</div> <div id='" + childId + '_' + linkName + "' class=\"content\">";
        for (var j in questionObj) {
            var tempQ = questionObj[j];
            if (tempQ.type == "checkBox") {
                html += " <input onchange='checkBoxChange(\""+childId+"\",\""+linkName+"\",\""+tempQ.key+"\")' type=\"checkbox\" "+((oldScore!=null && 'on'==oldScore[tempQ.key])?'checked':'')+" name=\"" + childId + '_' + linkName + '_' + tempQ.key + "\"> " + tempQ.lable + "  <br />";
            }
            if (tempQ.type == "select") {
                var optionArr = questionObj[j]["option"];
                html += " <select onchange='selectChange(\""+childId+"\",\""+linkName+"\",\""+tempQ.key+"\")'  name=\"" + childId + '_' + linkName + '_' + tempQ.key + "\" class=\"form-control\">";
                html+="<option value=\"\">请选择</option>";
                for(var k in optionArr){
                    html+="<option value="+optionArr[k].value+" "+((oldScore!=null && optionArr[k].value==oldScore[tempQ.key])?'selected':'')+" >"+optionArr[k].text+"</option>";
                }


                html +="</select> <br>";
            }
            if (tempQ.type == "input") {
                var str =(oldScore==null?"":oldScore[tempQ.key]);
                if(str == undefined){
                    str="";
                }
                if(tempQ.key  == 'yfzgs' || tempQ.key  == 'cxpqgs'){
                    html += "<input onchange='selectChange(\""+childId+"\",\""+linkName+"\",\""+tempQ.key+"\")'  name=\"" + childId + '_' + linkName + '_' + tempQ.key + "\"  type=\"number\" class=\"form-control\" value=\""+str+"\"  placeholder=\"" + tempQ.lable + "\">";
                }else {
                    html += "<input onchange='selectChange(\""+childId+"\",\""+linkName+"\",\""+tempQ.key+"\")'  name=\"" + childId + '_' + linkName + '_' + tempQ.key + "\"  type=\"text\" class=\"form-control\" value=\""+str+"\"  placeholder=\"" + tempQ.lable + "\">";
                }
            }
            if (tempQ.type == "textarea") {
                var str =(oldScore==null?"":oldScore[tempQ.key]);
                if(str == undefined){
                    str="";
                }
                var areaName=childId + '_' + linkName + '_' + tempQ.key;
                if(childId !=0){
                    html += "<div  name=\"" +areaName + "\"  class=\"form-control summernote\"  placeholder=\"" + tempQ.lable + "\" >"+str+"</div> ";
                }
                bzName.push(areaName)
            }
        }
        html += "</div></div>";
        return html;
    }

    function checkBoxChange(childId,linkName,questionKey) {
        $("#title_"+childId+"_"+linkName).removeClass('title-red');
        //全部学生操作时，全部赋值
        var allName = childId + '_' + linkName + '_' + questionKey;
        var localValue = $("[name='"+allName+"']").is(':checked');
        if(childId==0){
            for(var i in childIds){
                var tempName = childIds[i] + '_' + linkName + '_' + questionKey;
                if(localValue){
                    $("[name='"+tempName+"']").prop("checked",true);
                }else {
                    $("[name='"+tempName+"']").prop("checked", false);
                }
                $("#title_"+childIds[i]+"_"+linkName).removeClass('title-red');
            }
        }
    }

    function selectChange(childId,linkName,questionKey) {
        $("#title_"+childId+"_"+linkName).removeClass('title-red');
        //全部学生操作时，全部赋值
        var allName = childId + '_' + linkName + '_' + questionKey;
        var localValue = $("[name='"+allName+"']").val();
        if(childId==0){
            for(var i in childIds){
                var tempName = childIds[i] + '_' + linkName + '_' + questionKey;
                $("[name='"+tempName+"']").val(localValue);
                $("#title_"+childIds[i]+"_"+linkName).removeClass('title-red');
                if(questionKey=="wcxll"){
                    if(localValue=="1" ){
                        $("[name^='"+childIds[i] + '_' + linkName+"']").attr("disabled",true);
                        $("[name^='"+tempName+"']").removeAttr("disabled");
                        $("[name^='"+childIds[i] + '_' + linkName+"']").val("");
                        $("[name^='"+childIds[i] + '_' + linkName+"']").removeAttr("checked")
                        $("[name='"+childIds[i] + '_' + linkName+ '_' + questionKey+"']").val(localValue);
                    }else {
                        $("[name^='"+childIds[i] + '_' + linkName+"']").removeAttr("disabled");
                    }
                }
            }
        }
        //选择未做时，除了备注，其余不可编辑
        if(questionKey=="wcxll"){
            if(localValue=="1" ){
                $("[name^='"+childId + '_' + linkName+"']").attr("disabled",true);
                $("[name^='"+allName+"']").removeAttr("disabled");
                $("[name^='"+childId + '_' + linkName+"']").val("");
                $("[name^='"+childId + '_' + linkName+"']").removeAttr("checked")
                $("[name='"+allName+"']").val(localValue);
            }else {
                $("[name^='"+childId + '_' + linkName+"']").removeAttr("disabled");
            }
        }
    }


    function saveScore() {
        $.modal.loading("数据提交中，请稍后...");
        var reqData =getParam(0);
        reqData.scoreFlag =0;
        //保存选择项目
        $.ajax({
            url: prefix + "/saveScore",
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(reqData),
            error: function (request) {
                $.modal.closeLoading();
                $.modal.alertError("系统错误");
            },
            success: function (data) {
                $.modal.closeLoading();
                $.modal.msg("保存成功");
            }
        })

    }

    function submitScore(){
        $.modal.confirm('确定提交吗？提交后不可更改。',function () {
            $.modal.loading("数据提交中，请稍后...");
            var reqData =getParam(1);
            reqData.scoreFlag =1;
            //保存选择项目
            $.ajax({
                url: prefix + "/saveScore",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(reqData),
                error: function (request) {
                    $.modal.closeLoading();
                    $.modal.alertError("系统错误");
                },
                success: function (data) {
                    $.modal.closeLoading();
                    $("#saveScoreBth").css("display","none");
                    $.modal.msg("提交成功");
                }
            })
        });
    }

    function getParam(scoreFlag){
        var reqData = {
            "childCourseId": $("#childCourseId").val()
        }
        var data = $("#data-form").serializeJson();
        var scoreList = [];
        // childIds.forEach(function (childId)
        var submitFlag = false,redList=[],needScore={};
        for(var ix=0;ix < childIds.length;ix++){
            var childId = childIds[ix];
            if(childId ==0){
                continue;
            }
            var childScore = {"childId": childId};
            for (var i = 1; i <= 9; i++) {
                var key = childId + "_link" + i + "_"
                var linkTemp = {};
                $.each(data, function (name, value) {
                    if (name.indexOf(key) > -1) {
                        needScore[key]="1";
                        name = name.replace(key, "");
                        if(value !=""){
                            linkTemp[name] = value;
                        }
                    }
                });
                if(bzName.indexOf(childId + "_link" + i + "_bz")>-1){
                    needScore[key]="1";
                    var val= $("[name='"+childId + "_link" + i + "_bz"+"']").summernote('code');
                    if(val !="" && val !="<p><br></p>"){
                        linkTemp.bz = val;
                    }

                }

                if(JSON.stringify(linkTemp)==='{}'){
                    continue
                }

                if(i==1){childScore.linkOneScore=JSON.stringify(linkTemp);}
                if(i==2){childScore.linkTwoScore=JSON.stringify(linkTemp);}
                if(i==3){childScore.linkThreeScore=JSON.stringify(linkTemp);}
                if(i==4){childScore.linkFourScore=JSON.stringify(linkTemp);}
                if(i==5){childScore.linkFiveScore=JSON.stringify(linkTemp);}
                if(i==6){childScore.linkSixScore=JSON.stringify(linkTemp);}
                if(i==7){childScore.linkSevenScore=JSON.stringify(linkTemp);}
                if(i==8){childScore.linkEightScore=JSON.stringify(linkTemp);}
                if(i==9){childScore.linkNineScore=JSON.stringify(linkTemp);}
            }

            if(scoreFlag ==1){
                //1、引入≥2
                //2、主体项目（项目1-项目4）≥2
                //3、游戏+拉伸按摩≥1
                //2022-08-12修改为全部必填
                var req1=0,req2=0,req3=0;
                if(needScore[childId + "_link" + 1 + "_"]!=undefined && childScore.linkOneScore==undefined){req1+=1;redList.push('title_'+childId+'_link1');}
                if(needScore[childId + "_link" + 2 + "_"]!=undefined && childScore.linkTwoScore==undefined){req1+=1;redList.push('title_'+childId+'_link2');}
                if(needScore[childId + "_link" + 3 + "_"]!=undefined && childScore.linkThreeScore==undefined){req1+=1;redList.push('title_'+childId+'_link3');}
                if(needScore[childId + "_link" + 4 + "_"]!=undefined &&  childScore.linkFourScore ==undefined){req2+=1;redList.push('title_'+childId+'_link4');}
                if(needScore[childId + "_link" + 5 + "_"]!=undefined && childScore.linkFiveScore ==undefined){req2+=1;redList.push('title_'+childId+'_link5');}
                if(needScore[childId + "_link" + 6 + "_"]!=undefined && childScore.linkSixScore  ==undefined){req2+=1;redList.push('title_'+childId+'_link6');}
                if(needScore[childId + "_link" + 7 + "_"]!=undefined && childScore.linkSevenScore==undefined){req2+=1;redList.push('title_'+childId+'_link7');}
                if(needScore[childId + "_link" + 8 + "_"]!=undefined && childScore.linkEightScore==undefined){req3+=1;redList.push('title_'+childId+'_link8');}
                if(needScore[childId + "_link" + 9 + "_"]!=undefined && childScore.linkNineScore ==undefined){req3+=1;redList.push('title_'+childId+'_link9');}
                if(req1>0 || req2>0 || req3 > 0){
                    submitFlag =true;
                }
            }
            scoreList.push(childScore);
        };
        if(submitFlag){
            $.modal.alertWarning("成绩记录不完整，无法提交");
            $.modal.closeLoading();
            redList.forEach(function (redLink){
                $("#"+redLink).addClass('title-red');
            });
            return ;
        }
        reqData.scoreList = scoreList;
        return reqData;
    }

    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        var not_checked_object = $('input[type=checkbox]:not(:checked)', this);
        $.each(not_checked_object, function () {
            if (!array.hasOwnProperty(this.name)) {//this指没选中的一个object
                array.push({name: this.name, value: ""});
            }
        });
        $(array).each(
            function () {
                if (serializeObj[this.name]) {
                    if ($.isArray(serializeObj[this.name])) {
                        serializeObj[this.name].push(this.value);
                    } else {
                        serializeObj[this.name] = [
                            serializeObj[this.name], this.value];
                    }
                } else {
                    serializeObj[this.name] = this.value;
                }
            });
        return serializeObj;
    }

    function editBasicExpression(courseId,child) {
        var url = ctx + "business/courseChildScore/editBasicExpression/" + courseId+"/"+child;
        $.modal.open("基础表现", url,1200,780);
        $.table.refresh();
    }


</script>
</body>

</html>